package com.zbest.zpay.acctrans.share.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.zbest.common.lang.util.CoreSystemUtils;
import com.zbest.component.dal.sequence.DefaultSequenceFactory;
import com.zbest.zpay.acctrans.common.exception.AccTransRuntimeException;
import com.zbest.zpay.acctrans.dal.mapper.RunStsMapper;
import com.zbest.zpay.acctrans.dal.model.RunSts;
import com.zbest.zpay.acctrans.dal.model.TransJnl;
import com.zbest.zpay.acctrans.enums.biz.AcctransBizCode;
import com.zbest.zpay.acctrans.share.InitialTransactionService;

/**
 * Created by wenfeihu on 16/5/25.
 */
@Service("initialTransactionService")
public class InitialTransactionServiceImpl implements InitialTransactionService {
    private static final Logger logger = LoggerFactory
            .getLogger(InitialTransactionServiceImpl.class);

    @Autowired
    private RunStsMapper runStsMapper;

    @Autowired
    @Qualifier("acctransDefaultSequenceFactory")
    private DefaultSequenceFactory defaultSequenceFactory;

    @Override
    public void init(TransJnl transJnl) {
        try {
            String actDat = getActDat();
            logger.info("初始化会计日期:" + actDat);
            transJnl.setActDat(actDat);
            String jrnNo = getJrnNo(actDat);
            logger.info("初始化流水号:" + jrnNo);
            transJnl.setJrnNo(jrnNo);
        } catch (Exception e) {
            logger.error("交易初始化数据异常", e);
            throw new AccTransRuntimeException(AcctransBizCode.ACT_DATA_TYPE_SWITCH_ERROR, e);
        }
        transJnl.setJrnSeq("1");
    }

    @Override
    public String getActDat() {
        String actDat = null;
        try {
            RunSts runSts = runStsMapper.qryRunSts();
            actDat = runSts.getCurAcDt();
        } catch (Exception e) {
            logger.error("获取会计日期异常", e);
            throw new AccTransRuntimeException(AcctransBizCode.ACT_GET_ACTDAT_FAIL, e);
        }
        return actDat;
    }

    private String getJrnNo(String actDat) {
        String jrnNo = null;
        try {
            String sequence = String.format("%016d",
                    defaultSequenceFactory.getNextValue("ACCTRANS_JRN_NO"));
            jrnNo = actDat + sequence;
        } catch (Exception e) {
            logger.error("获取流水号异常", e);
            throw new AccTransRuntimeException(AcctransBizCode.ACT_DATA_TYPE_SWITCH_ERROR, e);
        }
        return jrnNo;
    }

    @Override
    public String getHoldNo() {
        return CoreSystemUtils.objectId();
    }
}
